﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using ExitGames.Client.Photon.Lite;
using DICE_GS;


public class PvPMakeRoomSceneManager : LTEventListenerC {
	private static Queue<Dictionary<byte, object>> packetQueue = new Queue<Dictionary<byte, object>>();
	public static bool isMaster;

	public GameObject themeSelectSceneObject;
	public GameObject makeRoomSceneObject;
	
	public PvPReadyRoomPlayerSlot[] playerSlots;

	public PvPReadyRoomUnitBar[] unitBars;
	
	public GameObject readyButton;
	public GameObject startButton;
	
	public Dictionary<int,SlotInfo> slotInfoDic = new Dictionary<int, SlotInfo>();
	
	public GameObject selectFriendWindow;

	public UISprite teamRankImage;
	public UILabel teamHPLabel;

	public UISprite[] skillIcon;
	public UISprite tempSkillIcon;
	public UILabel tempSkillDesc;

	public UILabel selectedDropdownItemLabel;
	public GameObject selectCurrentDeckDropDownList;

	public BuyTempSkillWindow buyTempSkillWindow;

	public UILabel[] mapThemeName;
	public UILabel[] mapDesc;
	public UILabel[] mapName;

	public GameObject[] makeRoomButton;
	public GameObject[] randomRoomButton;	

	public GameObject[] deckDropDownListItem;

	List<string> currentUserNameList = new List<string>();

    int mySlotIndex = -1;

	public static bool isMakeRoom = false;

    public UISprite[] themeButtonBackground;
	
	// Use this for initialization
	void Start () {
		//temporary setup 

//		if( isMaster )
//		{
//			playerSlots[0].playerImage.spriteName = "Char0"+MyInfo.Instance.pawnId;
////			playerSlots[0].checkImage.
//			playerSlots[0].playerName.text = MyInfo.Instance.NickName;
//			if( MyInfo.Instance.userLevel > 0 )
//				playerSlots[0].playerLevel.text = "LV."+MyInfo.Instance.userLevel;
//			else
//				playerSlots[0].playerLevel.text = "LV.1";
//            playerSlots[0].masterMark.gameObject.SetActive(true);
////			playerSlots[0].readyLabel.gameObject.SetActive(false);
////			playerSlots[0].loadingLabel.gameObject.SetActive(true);
////			PC_OP_CHANGE_READY_STATUS packet = new PC_OP_CHANGE_READY_STATUS();
////
////			CNetworkManager.Instance.SendPacket(packet);
//			playerSlots[0].playerInfo.SetActive(true);
//			playerSlots[0].blank.SetActive(false);
//		}

//		RefreshDeckInfo();
		mapThemeName[0].text = CStringTableManager.Instance.GetItemById(2364);
		mapThemeName[1].text = CStringTableManager.Instance.GetItemById(2365);
		mapThemeName[2].text = CStringTableManager.Instance.GetItemById(2366);
		mapName[0].text = CStringTableManager.Instance.GetItemById(2357);
		mapName[1].text = CStringTableManager.Instance.GetItemById(2363);
		mapName[2].text = CStringTableManager.Instance.GetItemById(2359);
		mapDesc[0].text = CStringTableManager.Instance.GetItemById(2356);
		mapDesc[1].text = CStringTableManager.Instance.GetItemById(2362);
		mapDesc[2].text = CStringTableManager.Instance.GetItemById(2358);
        Debug.LogError("is_PVE == " + StageManagerWrapper.is_PVE);

        if (StageManagerWrapper.is_PVE)
        {
            themeSelectSceneObject.SetActive(false);
            makeRoomSceneObject.SetActive(true);

            RefreshDeckInfo();

            if (MyInfo.Instance.currentDeckInfo.currentActivateCardCount == 0)
            {
                if (isMaster)
                    startButton.SetActive(false);
                else
                    readyButton.SetActive(false);
                MessagePopup.window.ShowPopup(MESSAGEPOPUPTYPE.NoSettingTeam, null, null);
            }
        }
	}

	public void RefreshDeckInfo()
	{
		DeckInfo deckInfo = MyInfo.Instance.currentDeckInfo;

		selectedDropdownItemLabel.text = deckDropDownListItem[MyInfo.Instance.MyCurrentDeck].GetComponentInChildren<UILabel>().text;
		
		int totalHP = 0;
		int totalgrade = 0;
		for(int i=0; i<deckInfo.SlotMap.Count; i++)
		{
			unitBars[i].unitName.text = deckInfo.SlotMap[i].name;
			unitBars[i].unitLevel.text = deckInfo.SlotMap[i].UnitLevel.ToString();
			unitBars[i].unitCost.text = deckInfo.SlotMap[i].cost.ToString();
			unitBars[i].unitHP.text = deckInfo.SlotMap[i].hp.ToString();
			for(int j=0; j<deckInfo.SlotMap[i].grade; j++)
				unitBars[i].gradeMark[j].SetActive(true);
			totalHP += deckInfo.SlotMap[i].hp;
			totalgrade += deckInfo.SlotMap[i].grade;
			if( deckInfo.SlotMap[i].UnitDBID == 0 )
				unitBars[i].gameObject.SetActive(false);
			else
				unitBars[i].gameObject.SetActive(true);
		}
		
		if( totalgrade / 5 >= 5 )
			teamRankImage.spriteName = "ScoreA_SS";
		else if( (totalgrade / 5) < 5 && (totalgrade / 5) >= 4 )
			teamRankImage.spriteName = "ScoreA_S";
		else if( (totalgrade / 5) < 4 && (totalgrade / 5) >= 3 )
			teamRankImage.spriteName = "ScoreA_A";
		else if( (totalgrade / 5) < 3 && (totalgrade / 5) >= 2 )
			teamRankImage.spriteName = "ScoreA_B";
		else if( (totalgrade / 5) < 2 && (totalgrade / 5) >= 1 )
			teamRankImage.spriteName = "ScoreA_C";
		else
			teamRankImage.spriteName = "ScoreA_D";
		teamHPLabel.text = totalHP.ToString();
		
		skillIcon[0].spriteName = deckInfo.skill1_IconName;
		skillIcon[1].spriteName = deckInfo.skill2_IconName;

		if( MyInfo.Instance.currentDeckInfo.currentActivateCardCount == 0 )
		{
			if( isMaster )
				startButton.SetActive(false);
			else
				readyButton.SetActive(false);
			MessagePopup.window.ShowPopup(MESSAGEPOPUPTYPE.NoSettingTeam, null, null);
		}
		else
		{
            if (!isMaster)
                readyButton.SetActive(true);
            else
            {
                if (isReadyForStartGame)
                    startButton.SetActive(true);
            }
		}
	}

    bool isReadyForStartGame = false;
	// Update is called once per frame
	void Update () {
		while (packetQueue.Count > 0)
        {
            Dictionary<byte, object> tmpPacket = packetQueue.Dequeue();

            switch ((byte)tmpPacket[0])
            {
                #region OperationCodes.SC_SHOW_UI:
                case (byte)OperationCodes.SC_SHOW_UI:
                {
                    PC_SC_SHOW_UI packet = new PC_SC_SHOW_UI(tmpPacket);

                    if (packet.UIType == (byte)UIType.UI_GAME_START)
                    {
                        glog.debug("Show GameStart!!!!");
                        isReadyForStartGame = true;
						if( MyInfo.Instance.currentDeckInfo.currentActivateCardCount != 0 )
							startButton.gameObject.SetActive(true);
                    }
                }
                break;
                #endregion
                #region OperationCodes.SC_HIDE_UI:
                case (byte)OperationCodes.SC_HIDE_UI:
                {
                    PC_SC_HIDE_UI packet = new PC_SC_HIDE_UI(tmpPacket);

                    if (packet.UIType == (byte)UIType.UI_GAME_START)
                    {
                        glog.debug("Hide GameStart!!!!");
                        isReadyForStartGame = false;
						startButton.gameObject.SetActive(false);
                    }
                }
                break;
                #endregion

                #region OperationCodes.OP_CHANGE_READY_STATUS:
                case (byte)OperationCodes.OP_CHANGE_READY_STATUS:
                {
                	PC_OP_CHANGE_READY_STATUS packet = new PC_OP_CHANGE_READY_STATUS(tmpPacket);
					
                    if (packet.Status == (byte)ReadyStatus.RS_READY)
                    {
                        //레디중
                        isMaster = packet.IsMaster;
						glog.debug("Ready - " + isMaster);
                        if (!isMaster)
                        {
							if( MyInfo.Instance.currentDeckInfo.currentActivateCardCount != 0 )
							{
	                            readyButton.gameObject.SetActive(true);
								readyButton.gameObject.GetComponentInChildren<UILabel>().text = CStringTableManager.Instance.GetItemById(1638);
								readyButton.gameObject.GetComponentInChildren<UILabel>().color = new Color(225f/255f,180f/255f,66f/255f);
							}
                        }
                        else
                        {
                            if( mySlotIndex > -1 )
                                playerSlots[mySlotIndex].masterMark.gameObject.SetActive(true);
                            readyButton.gameObject.SetActive(false);
                        }
                    }
                    else
                    {
                        //레디아님
                        isMaster = packet.IsMaster;
                        glog.debug("Not Ready - " + isMaster);
                        if (!isMaster)
                        {
							if( MyInfo.Instance.currentDeckInfo.currentActivateCardCount != 0 )
							{
								readyButton.gameObject.SetActive(true);
								readyButton.gameObject.GetComponentInChildren<UILabel>().text = CStringTableManager.Instance.GetItemById(2371);
								readyButton.gameObject.GetComponentInChildren<UILabel>().color = new Color(45f/255f,39f/255f,29f/255f);
							}
						}
						else
						{
                            if (mySlotIndex > -1)
                                playerSlots[mySlotIndex].masterMark.gameObject.SetActive(true);
                            readyButton.gameObject.SetActive(false);
                        }
                    }
                }
                break;
                #endregion

                #region OperationCodes.OP_LOBBY_STATUS:
                case (byte)OperationCodes.OP_LOBBY_STATUS:
                {
					slotInfoDic.Clear();
					foreach(PvPReadyRoomPlayerSlot slot in playerSlots)
						slot.playerInfo.gameObject.SetActive(false);
                    PC_OP_LOBBY_STATUS packet = new PC_OP_LOBBY_STATUS(tmpPacket);
					Debug.LogError("packet.UserCount : " + packet.UserCount);
//					readyState.ResetState();
                    for (int i = 0; i < packet.UserCount; i++)
                    {
                        glog.debug("ConnectionID :" + packet.ConnectionIDList[i] + " Username: " + packet.UserNameList[i]+" Ready: " + packet.ReadyStatus[i]+" slot: "+packet.SlotInfo[i]);
                        glog.debug("LEADERID : "+packet.LeaderIDLIst[i]); 

						//readyState.SetLeaderImg(i, packet.LeaderIDLIst[i]);
						//glog.debug("Username: " + packet.UserNameList[i]);
                        //glog.debug("UserLevel: " + packet.UserLevelList[i]);
                        //glog.debug("LeaderID: " + packet.LeaderIDLIst[i]);
                        //glog.debug("Ready: " + packet.ReadyStatus[i]);
						//readyState.SetState(i, packet.UserNameList[i] , (int)packet.ReadyStatus[i]);
						if( slotInfoDic.ContainsKey(packet.ConnectionIDList[i]))
						{
							glog.debug("containKeys "+packet.ConnectionIDList[i]);
							slotInfoDic[ packet.ConnectionIDList[i] ].SetOccupy((int)packet.ReadyStatus[i]);
						}
						else {
							glog.debug("Not containKeys "+packet.ConnectionIDList[i]);
							string nickForTest = packet.UserNameList[i];// + packet.ConnectionIDList[i];
							slotInfoDic[packet.ConnectionIDList[i]] = new SlotInfo(packet.SlotInfo[i], nickForTest, (int)packet.ReadyStatus[i], packet.LeaderIDLIst[i]);
						}
						
						if( !currentUserNameList.Contains(packet.UserNameList[i]) )
							currentUserNameList.Add(packet.UserNameList[i]);
                    }

                    /*
                     
                    */
                    if (packet.Element == (byte)element.earth)
                    {
                        CSceneManager.StageElement = "earth";
                    }
                    else if (packet.Element == (byte)element.ocean)
                    {
                        CSceneManager.StageElement = "ocean";
                    }
                    else if (packet.Element == (byte)element.sky)
                    {
                        CSceneManager.StageElement = "sky";
                    }
                    else
                    {
                        CSceneManager.StageElement = "random";
                    }
					
					int keyToDelete = 0;
					bool bDeleteKey = false;

					foreach(int key in slotInfoDic.Keys)
						Debug.LogError(key);

					for(int j=0; j<packet.ConnectionIDList.Length; j++)
//					foreach (KeyValuePair<int, SlotInfo> pair in slotInfoDic)
					{
						SlotInfo slotInfo = slotInfoDic[packet.ConnectionIDList[j]];
						Debug.Log(slotInfo.index);
						if(playerSlots[slotInfo.index] == null )
							Debug.LogError("playerSlots[slotInfo.index] is null!");
						if(slotInfo.isOccupied) {
//							readyState.SetSlot(slotInfo.index, slotInfo.nickname , slotInfo.ready, slotInfo.leaderUnitClassId);
							playerSlots[slotInfo.index].playerImage.spriteName = string.Format("IngameUi_cha{0:00}", slotInfo.leaderUnitClassId);
							playerSlots[slotInfo.index].playerName.text = slotInfo.nickname;
							playerSlots[slotInfo.index].playerLevel.text = "";
							if( slotInfo.ready == 1 )
							{
//								playerSlots[slotInfo.index].readyLabel.gameObject.SetActive(true);
//								playerSlots[slotInfo.index].loadingLabel.gameObject.SetActive(false);
								playerSlots[slotInfo.index].readyMark.gameObject.SetActive(true);
//								playerSlots[slotInfo.index].backgroundImage.spriteName = "UI_btn02s";
							}
							else
							{
//								playerSlots[slotInfo.index].readyLabel.gameObject.SetActive(false);
//								playerSlots[slotInfo.index].loadingLabel.gameObject.SetActive(true);
								playerSlots[slotInfo.index].readyMark.gameObject.SetActive(false);
//								playerSlots[slotInfo.index].backgroundImage.spriteName = "UI_btn03s";
							}
							playerSlots[slotInfo.index].playerInfo.SetActive(true);
							playerSlots[slotInfo.index].blank.SetActive(false);
						
							if( packet.ConnectionIDList[slotInfo.index] == packet.MasterConnectionID )
                            {
                                Debug.LogError("ConnectionIDList[j] : " + packet.ConnectionIDList[j]);
                                Debug.LogError("MasterConnectionID : " + packet.MasterConnectionID);
                                playerSlots[slotInfo.index].masterMark.gameObject.SetActive(true);
                            }
							else
							{
								Debug.LogError("ConnectionIDList[j] : " + packet.ConnectionIDList[j]);
								Debug.LogError("MasterConnectionID : " + packet.MasterConnectionID);
								playerSlots[slotInfo.index].masterMark.gameObject.SetActive(false);
							}
						
							if (slotInfo.nickname.Equals(MyInfo.Instance.NickName))
							{
								mySlotIndex = slotInfo.index;
	//                                playerSlots[slotInfo.index].masterMark.gameObject.SetActive(true);
	                            }
								glog.debug("occupied setSlot "+slotInfo.index);
							}
						else 
						{
							bDeleteKey = true;
							keyToDelete = j;
							glog.debug("delete key: "+ keyToDelete+ " clearSlotIndex "+slotInfo.index);
//							readyState. ClearSlot(slotInfo.index);
							playerSlots[slotInfo.index].playerInfo.SetActive(false);
							playerSlots[slotInfo.index].blank.SetActive(true);
						}

						for(int i=0; i<4; i++)
						{
							if( !playerSlots[i].playerInfo.activeSelf )
							{
								playerSlots[i].blank.SetActive(true);
								playerSlots[i].masterMark.gameObject.SetActive(false);
							}
						}
					}
					if(bDeleteKey)
						slotInfoDic.Remove(keyToDelete);
                }
                break;
                #endregion
                case (byte)OperationCodes.SC_CHANGE_GAME_STATUS:
                {
                    PC_SC_CHANGE_GAME_STATUS packet = new PC_SC_CHANGE_GAME_STATUS(tmpPacket);
					if ((GameStatus)packet.Status == GameStatus.GS_PLAYING || (GameStatus)packet.Status == GameStatus.GS_PRE_PLAY)
                    {
                        StageManagerWrapper.m_Connected = true;

                        StageManagerWrapper.Instance.SetStatus((GameStatus)packet.Status);

//						if (CSceneManager.m_Scene != SCENE.SummonMenuScene9)
						{
							CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
							c.GoToStageScene();
						}
                    }
                }
                break;
				case (byte)OperationCodes.OP_JOIN:
				{
					PC_OP_JOIN recvPacket = new PC_OP_JOIN(tmpPacket);

					if (recvPacket.JoinResult == (byte)JoinResult.SUCCESS)
					{
						isMakeRoom = true;
						StageManagerWrapper.m_Connected = true;
						StageManagerWrapper.is_PVE = false;	
						if (recvPacket.IsRoomMaster)
						{
							PvPMakeRoomSceneManager.isMaster = true;
							themeSelectSceneObject.SetActive(false);
							makeRoomSceneObject.SetActive(true);

							playerSlots[0].playerImage.spriteName = "Char0"+MyInfo.Instance.pawnId;
							playerSlots[0].playerName.text = MyInfo.Instance.NickName;
							if( MyInfo.Instance.userLevel > 0 )
								playerSlots[0].playerLevel.text = "LV."+MyInfo.Instance.userLevel;
							else
								playerSlots[0].playerLevel.text = "LV.1";
				            playerSlots[0].masterMark.gameObject.SetActive(true);
							playerSlots[0].playerInfo.SetActive(true);
							playerSlots[0].blank.SetActive(false);
						}
						else
						{
							PvPMakeRoomSceneManager.isMaster = false;
							themeSelectSceneObject.SetActive(false);
							makeRoomSceneObject.SetActive(true);
						}

						RefreshDeckInfo();

                        LoadingWindow.window.HideLoading();
					}
				}
				break;
                default:
                    glog.debug("PvPMakeRoomSceneManager's Packet Handler Unknown Packet Recieved [" + (byte)tmpPacket[0] + "]");
                    break;
            }
        }
	}
	
	public static bool PacketHandler(Dictionary<byte, object> _packet)
    {
        glog.debug("PvPMakeRoomSceneManager Got Packet");
        if (packetQueue != null)
        {
            packetQueue.Enqueue(_packet);
            return true;
        }

        return false;
    }

	int _selectedModeIndex = -1;
	public override void OnEvent (int eventID)
	{
		Debug.LogError(eventID);
		base.OnEvent (eventID);
		
		if( eventID > 9 && eventID < 20)
		{
			if( MyInfo.Instance.MyDeckMap.ContainsKey(eventID-10) )
			{
				selectedDropdownItemLabel.text = deckDropDownListItem[eventID-10].GetComponentInChildren<UILabel>().text;
				MyInfo.Instance.MyCurrentDeck = eventID - 10;
				Debug.LogError(MyInfo.Instance.currentDeckInfo.deckId);
				RefreshDeckInfo();
			}

			TweenScale twScale = selectCurrentDeckDropDownList.GetComponent<TweenScale>();
			twScale.from = new Vector3(1f,1f,1f);
			twScale.to = new Vector3(1f,0f,1f);
			twScale.delay = 0f;
			twScale.duration = 0.3f;
			twScale.enabled = true;
			twScale.PlayForward();
		}
		else if( eventID >= 20 )
		{
			if( _selectedModeIndex > -1 )
			{
				makeRoomButton[_selectedModeIndex].SetActive(false);
				randomRoomButton[_selectedModeIndex].SetActive(false);
                themeButtonBackground[eventID - 20].color = Color.white;
			}

			if(eventID-20 == 0)
				CSceneManager.m_mapName = "map_pvp1";
			else if(eventID-20 == 1)
				CSceneManager.m_mapName = "map_pvp2";
			else if(eventID-20 == 2)
				CSceneManager.m_mapName = "map_pvp3";

            themeButtonBackground[eventID-20].color = new Color(152f/255f, 152f/255f, 152f/255f);
			makeRoomButton[eventID-20].SetActive(true);
			randomRoomButton[eventID-20].SetActive(true);
			_selectedModeIndex = eventID-20;
		}
	}

	void OnClickTempSkillBuyButton()
	{
		buyTempSkillWindow.gameObject.SetActive(true);
	}

	public void SetTempSkillInfo(int skillId)
	{
		CSkillData skillData = CSkillDataManager.Instance.FindSkillData(skillId);
		if( skillData != null )
		{
			tempSkillIcon.spriteName = skillData.icon_name;
			tempSkillIcon.transform.parent.gameObject.SetActive(true);
			tempSkillDesc.text = CStringTableManager.Instance.GetItemByName(skillData.name_string);
		}
	}
	
	void OnClickRandomButton()
	{
	}
	
	void OnClickExitButton()
	{
		if( isMakeRoom )
			StageManagerWrapper.SendLeave();
		else
			CSceneManager.manager.GoToWaitroomScene();
	}
	
	void OnClickReadyButton()
	{
		PC_OP_CHANGE_READY_STATUS packet = new PC_OP_CHANGE_READY_STATUS();
		packet.UseDeckID = MyInfo.Instance.currentDeckInfo.deckId;
		Debug.LogError(packet.UseDeckID);

		CNetworkManager.Instance.SendPacket(packet);
	}
	
	void OnClickStartButton()
	{
		LoadingWindow.window.ShowShortLoading();
		PC_OP_GAME_START packet = new PC_OP_GAME_START();
		packet.UseDeckID = MyInfo.Instance.currentDeckInfo.deckId;
		Debug.LogError(packet.UseDeckID);

		CNetworkManager.Instance.SendPacket(packet);
	}
	
	void TempMakeAI()
	{
		if (CNetworkManager.Instance.Connected)
		{
			if (!StageManagerWrapper.bOrdered)
			{
				StageManagerWrapper.MakeAIRunner();
			}
		}	
	}

	void OnClickDropDown()
	{
		for(int i=0; i<5; i++)
		{
			if( !MyInfo.Instance.MyDeckMap.ContainsKey(i) )
				deckDropDownListItem[i].SetActive(false);
		}

		TweenScale twScale = selectCurrentDeckDropDownList.AddComponent<TweenScale>();
		twScale.from = new Vector3(1f,0f,1f);
		twScale.to = new Vector3(1f,1f,1f);
		twScale.delay = 0f;
		twScale.duration = 0.3f;
		twScale.PlayForward();
	}

	void ReturnCallbak(Hashtable returnData)
	{
	}

	public void OnClickInviteFriend()
	{
		selectFriendWindow.SetActive(true);
	}

	public void ClostSelectFriendWindow()
	{
		selectFriendWindow.SetActive(false);
	}
}
